﻿using BackData;
using Details.API.Application.Command.Goods;
using Details.API.DTOs;
using Domain;
using Infratructure.RepositoryWay;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using NPOI.HSSF;
using NPOI.XSSF;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using Yitter.IdGenerator;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;

/// <summary>
/// 商品控制器
/// </summary>
namespace Details.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]  //授权启动
    public class GoodsController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IConfiguration configuration;
        private readonly IWebHostEnvironment web;
        private readonly IRepository<GoodsModel> goodway;

        public GoodsController(IMediator mediator, IConfiguration configuration, IWebHostEnvironment web, IRepository<GoodsModel> goodway)
        {
            this.mediator = mediator;
            this.configuration = configuration;
            this.web = web;
            this.goodway = goodway;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="request">商品信息</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<int>> AddGoods(AddGoodsCommand request)
        {

            return await mediator.Send(request);
        }
        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public Task<APIPaging<GoodsDTO>> GetGoods([FromQuery] GetGoodsCommand request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 修改商品
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        [HttpPut]
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<int>> UpdateGoods(UpdateGoodsCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="request">id</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        [HttpPut]
        public async Task<APIResult<int>> DelGoods(DelGoodsCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file">图片 </param>
        /// <returns>图片路径</returns>
        [HttpPost("IFormFile")]
        public IActionResult Upload(IFormFile file)
        {
            var id = YitIdHelper.NextId();  //雪花id
            var excep = Path.GetExtension(file.FileName);  //文件扩展名
            //var exception = file.FileName.Split(".");  // 文件名
            //var value = exception[1];  // 文件扩展名
            var way = $"{id}.{excep}";  // 拼接文件名
            var path = web.WebRootPath + "/Img/" + way;  // 保存路径, 这里使用雪花id作为文件名防止重复

            using (var fs = (System.IO.File.Create(path)))  // 创建文件
            {
                file.CopyTo(fs);  // 写入文件
                fs.Flush();  // 刷新缓冲区
            }
            return Ok("http://localhost:5196/Img/" + way);  // 返回图片路径
        }




        /// <summary>
        /// 导出商品列表为 Excel 文件
        /// </summary>
        /// <returns>返回 Excel 文件流（.xlsx 格式）</returns>
        [HttpGet]
        public IActionResult DownGoods(int number)
        {
            byte[] valuefile = null;
      
            var book = new XSSFWorkbook();  //创建工作簿
            var sheet = book.CreateSheet("商品信息");  //创建工作表
            var row = sheet.CreateRow(0);//创建行
            row.CreateCell(0).SetCellValue("商品主键");
            row.CreateCell(1).SetCellValue("生产批次");
            row.CreateCell(2).SetCellValue("保质期");
            row.CreateCell(3).SetCellValue("生产许可证号");
            row.CreateCell(4).SetCellValue("生产企业");
            row.CreateCell(5).SetCellValue("封面(图片路径)");
            row.CreateCell(6).SetCellValue("检查报告(图片路径)");
            row.CreateCell(7).SetCellValue("完成状态");
            row.CreateCell(8).SetCellValue("创建人");
            row.CreateCell(9).SetCellValue("创建时间");
            row.CreateCell(10).SetCellValue("修改人");
            row.CreateCell(11).SetCellValue("养殖外键");
            row.CreateCell(12).SetCellValue("屠宰外键");
            row.CreateCell(13).SetCellValue("深加工外键");
            // 1. 准备要导出的数据（实际项目中通常从数据库查询）
            var value = goodway.GetAll().Where(x => x.IsDel == false).Take(number).ToList();
            int i = 0;
            for (i = 0; i < value.Count(); i++)  //循环添加数据到行里
            {
                row = sheet.CreateRow(i + 1);

                row.CreateCell(0).SetCellValue(value[i].Goodsname.ToString());
                row.CreateCell(1).SetCellValue(value[i].Order.ToString());
                row.CreateCell(2).SetCellValue(value[i].Expired.ToString());
                row.CreateCell(3).SetCellValue(value[i].Allownum);
                row.CreateCell(4).SetCellValue(value[i].Companyname);
                row.CreateCell(5).SetCellValue(value[i].Cover);
                row.CreateCell(6).SetCellValue(value[i].Check);
                row.CreateCell(7).SetCellValue(value[i].Finiststate);
                row.CreateCell(8).SetCellValue(value[i].Creator);
                row.CreateCell(9).SetCellValue(value[i].Createtime.ToString());
                row.CreateCell(10).SetCellValue(value[i].Modifier);
                row.CreateCell(11).SetCellValue(value[i].Breedid.ToString());
                row.CreateCell(12).SetCellValue(value[i].Killid.ToString());
                row.CreateCell(13).SetCellValue(value[i].Deepprocessid.ToString());
            }
            using (var  streams=new MemoryStream())
            {
                book.Write(streams);
                valuefile=streams.ToArray();
                return File(valuefile, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "商品列表.xlsx");
            }

        }










    }
}
